import type { AsyncVoid, PromiseBoolean } from '../define/types'
import type IColumn from '../define/column'
import knex from '../connection'
import transaction from './transaction'

class Column implements IColumn {
  async add(table: string, name: string, type: string): AsyncVoid {
    return transaction.runInTransaction(async (trx) => {
      await trx.schema.table(table, (table: any) => {
        table.specificType(name, type)
      })
    })
  }

  async drop(table: string, name: string): AsyncVoid {
    return transaction.runInTransaction(async (trx) => {
      await trx.schema.table(table, (table: any) => {
        table.dropColumn(name)
      })
    })
  }

  async exists(table: string, name: string): PromiseBoolean {
    return await knex.schema.hasColumn(table, name)
  }

  async rename(table: string, from: string, to: string): AsyncVoid {
    return transaction.runInTransaction(async (trx) => {
      await trx.schema.table(table, (table: any) => {
        table.renameColumn(from, to)
      })
    })
  }
}

export default new Column()